package com.xgs.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgs.common.utils.DateUtils;
import com.xgs.common.utils.SecurityUtils;
import com.xgs.system.domain.Fee;
import com.xgs.system.domain.Lane;
import com.xgs.system.mapper.FeeMapper;
import com.xgs.system.service.FeeService;
import com.xgs.system.service.LaneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JerryLu
 * @date 2024/10/23 11:01
 * @description 名单Fee信息Service业务层处理
 */
@Service
public class FeeServiceImpl extends ServiceImpl<FeeMapper, Fee> implements FeeService {
    @Autowired
    private LaneService laneService;

    @Override
    public List<Fee> query(Fee fee) {
        List<String> dates = new ArrayList<>();
        String dbName;
        if (!fee.getParams().isEmpty()) {
            dates = getDates(fee.getParams().get("time1").toString(), fee.getParams().get("time2").toString());
            dbName = DateUtils.parseDateToStr(DateUtils.YYYY, DateUtils.dateTime(DateUtils.YYYY, fee.getParams().get("time1").toString()));
        } else {
            dbName = DateUtils.dateTimeNow(DateUtils.YYYY);
        }
        String deptId = SecurityUtils.getLoginUser().getDeptId();

        Lane lane = new Lane();
        lane.setOrgId(deptId);
        List<Lane> laneList = laneService.queryList(lane);
        String fields = joinFields(laneList, ",");

        return this.baseMapper.dynamicSelect(dbName, dates, deptId, fields);
    }

    private String joinFields(List<Lane> list, String fieldDelimiter) {
        return list.stream().map(Lane::getStationHex).map(field -> "'" + field + "'").collect(Collectors.joining(","));
    }

    private List<String> getDates(String startDateStr, String endDateStr) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);
        LocalDate endDate = LocalDate.parse(endDateStr, formatter);

        List<String> dateList = new ArrayList<>();

        // 循环遍历日期范围
        while (!startDate.isAfter(endDate)) {
            // 格式化日期为yyyyMMdd
            String formattedDate = startDate.format(DateTimeFormatter.BASIC_ISO_DATE);
            dateList.add(formattedDate);

            // 增加一天
            startDate = startDate.plusDays(1);
        }

        return dateList;
    }
}
